package com.smartthinking.destinomusical;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.smartthinking.destinomusical.adapter.SongListAdapter;
import com.smartthinking.destinomusical.base.ListBaseActivity;
import com.smartthinking.destinomusical.extra.Query;
import com.smartthinking.destinomusical.interfaces.WSInterface;
import com.smartthinking.destinomusical.obj.Cancion;
import com.smartthinking.destinomusical.obj.Categoria;
import com.smartthinking.destinomusical.obj.SearchParams;
import com.smartthinking.destinomusical.ws.WSCallTask;

public class CancionPorCategoria extends ListBaseActivity implements WSInterface {

	int paginado = 0;
	Button adelante, atras;
	EditText search;
	String columna = "v.vid_nombre", que = "%25%25";
	Categoria cat;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.explorar);
		cat = getIntent().getParcelableExtra("padre");
		
		setTopBar(R.drawable.siguientenuevo, R.string.boton_ordenar,
				getString(R.string.boton_canciones)+"("+cat.getDescripcion()+")");
		
		new WSCallTask(this, this).execute(new SearchParams(3, Query.CancionXCategoriaPuntual(
				cat.getClave(),que,columna,paginado)));
		adelante = (Button) findViewById(R.id.adelante);
		atras = (Button) findViewById(R.id.atras);
		search = (EditText) findViewById(R.id.search);
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		
		search.setOnEditorActionListener(new OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
		    	if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		    		InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    		in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
			        buscar();
			        return true;
		        }
		        return false;
		    }
		});
	}
	
	
	//Paginacion
	public void paginacion(int total) {
		System.out.println("Pagina:" + paginado);
		if (paginado+1 > 1) {
			atras.setVisibility(View.VISIBLE);
		} else {
			atras.setVisibility(View.INVISIBLE);
		}
		int extra = total % 10 > 0 ? 1 : 0;
		int numpag = total / 10 + extra;
		if (paginado+1 < numpag && numpag > 1) {
			adelante.setVisibility(View.VISIBLE);
		} else {
			adelante.setVisibility(View.INVISIBLE);
		}

	}

	public void onClickSiguiente(View v) {
		paginado++;
		new WSCallTask(this, this).execute(new SearchParams(3, Query.CancionXCategoriaPuntual(
				cat.getClave(),que,columna,paginado)));
	}

	public void onClickAtras(View v) {
		paginado--;
		new WSCallTask(this, this).execute(new SearchParams(3, Query.CancionXCategoriaPuntual(
				cat.getClave(),que,columna,paginado)));
	}

	public void buscar() {
		paginado = 0;
		que = "%25" + search.getEditableText().toString() + "%25";
		new WSCallTask(this, this).execute(new SearchParams(3, Query.CancionXCategoriaPuntual(
				cat.getClave(),que,columna,paginado)));
	}

	Cancion cancion = null;
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		cancion = (Cancion) l.getItemAtPosition(position);
		Intent intent = new Intent(CancionPorCategoria.this, MenuSong.class);
		intent.putExtra("usuario", usuario);
		intent.putExtra("cancion", cancion);
		intent.putExtra("lista","no");
		intent.putParcelableArrayListExtra("canciones", new ArrayList<Cancion>());
		startActivity(intent);

	}

	

	Dialog dialog = null;

	public void onClickButtonFuncion(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.boton_ordenar));

		ListView modeList = new ListView(this);
		modeList.setBackgroundColor(Color.WHITE);
		modeList.setCacheColorHint(Color.WHITE);
		modeList.setOnItemClickListener(itemSelected);
		String[] stringArray = getResources().getStringArray(R.array.orderType);
		ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1,
				stringArray);
		modeList.setAdapter(modeAdapter);

		builder.setView(modeList);
		dialog = builder.create();
		dialog.show();
	}

	OnItemClickListener itemSelected = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			paginado = 0;
			switch (position) {
			case 0:
				columna = "v.vid_nombre";
				break;
			case 1:
				columna = "v.vid_artista";
				break;
//			case 2:
//				columna = "v.vid_year";
//				break;
			case 2:
				columna = "v.vid_codigo";
				break;

			}
			que = "%25" + search.getEditableText().toString() + "%25";
			// que="%25%25";
			
			new WSCallTask(CancionPorCategoria.this, CancionPorCategoria.this)
					.execute(new SearchParams(3, Query.CancionXCategoriaPuntual(
							cat.getClave(),que,columna,paginado)));
			if (dialog.isShowing())
				dialog.dismiss();
		}
	};

	@Override
	public void onWSInterfaceComplete(List<?> list) {
		if (list == null || list.size() == 0) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.msg_noResults), Toast.LENGTH_SHORT)
					.show();

		} else {
			SongListAdapter catListAdapter = new SongListAdapter(CancionPorCategoria.this,
					list);
			getListView().setAdapter(catListAdapter);
			int total = Integer.parseInt(((Cancion) list.get(0)).getTotal()
					.trim());
			paginacion(total);

		}

	}

	@Override
	public void onWSInterfaceCancel(boolean cancelado) {
		// TODO Auto-generated method stub

	}

	public void onClickLista(View view) {
		final Dialog dialog = new Dialog(CancionPorCategoria.this);
		dialog.setContentView(R.layout.song_dialog);
		dialog.setTitle("Reproducir:");
		Button dialogButton = (Button) dialog.findViewById(R.id.cancel);
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

}